package io.renren.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.renren.common.page.PageData;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.common.utils.ConvertUtils;
import io.renren.common.utils.Result;
import io.renren.dao.CollarDao;
import io.renren.dao.CollarmxDao;
import io.renren.dao.CollarmxTemDao;
import io.renren.dto.*;
import io.renren.entity.CollarEntity;
import io.renren.entity.UserEntity;
import io.renren.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 辅材领用表
 *
 * @author 罗胜平 781757616@qq.com
 * @since 1.0.0 2019-11-22
 */
@Service
public class CollarServiceImpl extends CrudServiceImpl<CollarDao, CollarEntity, CollarDTO> implements CollarService {
    @Autowired
    private  CollarService collarService;
    @Autowired
    private CollarmxService collarmxService;
    @Autowired
    private FoodmxService foodmxService;
    @Autowired
    private CollarmxDao collarmxDao;
    @Autowired
    private CollarDao collarDao;
    @Autowired
    private TemporaryOrderService temporaryOrderService;
    @Autowired
    private TemporaryOrdermxService temporaryOrdermxService;
    @Autowired
    private CollarmxTemService collarmxTemService;
    @Override
    public QueryWrapper<CollarEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");

        QueryWrapper<CollarEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);

        return wrapper;
    }

    @Transactional
    public  Result updateExamine(CollarDTO dto, UserEntity entity){
        //如果到货数量或者照片没有传抛出异常
        if(3==dto.getStatus()){
            //根据订单号查询详情 并遍历，判断空
            List<CollarmxDTO> collarmxList = collarmxService.seleCollarmx(dto.getCollarId());
            for (CollarmxDTO collarmxDTO:collarmxList) {

                    if (null == collarmxDTO.getArrivalNum() || StringUtils.isBlank(collarmxDTO.getEntityPhoto())) {
                        Result result = new Result();
                        return result;
                    }

            }
        }
        if (dto.getStatus()==4){
            dto.setStatus(5);
            dto.setConfirmDatetime(new Date());
            dto.setChedId(entity.getId());
        }
        if (dto.getStatus()==3){
            dto.setStatus(4);
            dto.setReceivingGoodsTime(new Date());
            dto.setStorehouseClerkId(entity.getId());
            sbuInventory(dto.getCollarId());
        }

        if (dto.getStatus()==1){
            dto.setStatus(3);
            dto.setAuditTime(new Date());
            dto.setCanteenAdminId(entity.getId());
        }
        update(dto);
        //减库存的操作
        return new Result();
    }



    /**
     * 根据订单号查询订单详情，根据订单详情减少库存
     * @param collarId
     */
    void sbuInventory(Long collarId){
         List<CollarmxDTO> collarmxList = collarmxService.seleCollarmx(collarId);
         for (CollarmxDTO collarmxDTO:collarmxList) {
             Float realCollarNum=0F;
             Float totalPrice=0F;//领取食材数量的总价用于保存
             realCollarNum = collarmxDTO.getArrivalNum();//实收数据量
             //实收数据量 与数据库中库存对比，如果实收数量 > 当前订单的库存 则减去当前库存，并删除当前记录
             List<FoodmxDTO> list = foodmxService.selectFoodIdmx(collarmxDTO.getFoodId());
             boolean ok = true;
             for (FoodmxDTO foodmxDTO: list) {
                 if(ok){
                     if(realCollarNum - foodmxDTO.getFoodNum()>0){//当前订单的库存 则减去当前库存，并删除当前记录
                         CollarmxTemDTO collarmxTemDTO = new CollarmxTemDTO();
                         collarmxTemDTO.setBatchNumber(foodmxDTO.getBatchNumber());
                         collarmxTemDTO.setCollarId(collarmxDTO.getCollarId());
                         collarmxTemDTO.setArrivalNum(foodmxDTO.getFoodNum());
                         collarmxTemDTO.setFoodId(collarmxDTO.getFoodId());
                         collarmxTemDTO.setFoodName(collarmxDTO.getFoodName());
                         collarmxTemDTO.setEntityPhoto(collarmxDTO.getEntityPhoto());
                         collarmxTemDTO.setUnitPrice(foodmxDTO.getUnitPrice());
                         collarmxTemDTO.setCollarNum(collarmxDTO.getCollarNum());
                         collarmxTemDTO.setTotalPrice(foodmxDTO.getUnitPrice()*foodmxDTO.getFoodNum());
                         collarmxTemService.save(collarmxTemDTO);
                         realCollarNum =  realCollarNum - foodmxDTO.getFoodNum();
                         totalPrice= foodmxDTO.getFoodNum()*foodmxDTO.getUnitPrice()+totalPrice;
                         foodmxService.delectFoodIdmx(foodmxDTO.getFoodmxId());
                         // 同时吧这条记录设置到领取表中
                     }else if(realCollarNum - foodmxDTO.getFoodNum()==0){
                         CollarmxTemDTO collarmxTemDTO = new CollarmxTemDTO();
                         collarmxTemDTO.setBatchNumber(foodmxDTO.getBatchNumber());
                         collarmxTemDTO.setCollarId(collarmxDTO.getCollarId());
                         collarmxTemDTO.setArrivalNum(foodmxDTO.getFoodNum());
                         collarmxTemDTO.setFoodId(collarmxDTO.getFoodId());
                         collarmxTemDTO.setFoodName(collarmxDTO.getFoodName());
                         collarmxTemDTO.setEntityPhoto(collarmxDTO.getEntityPhoto());
                         collarmxTemDTO.setUnitPrice(foodmxDTO.getUnitPrice());
                         collarmxTemDTO.setCollarNum(collarmxDTO.getCollarNum());
                         collarmxTemDTO.setTotalPrice(foodmxDTO.getUnitPrice()*foodmxDTO.getFoodNum());
                         collarmxTemService.save(collarmxTemDTO);
                         realCollarNum =  realCollarNum - foodmxDTO.getFoodNum();
                         totalPrice= foodmxDTO.getFoodNum()*foodmxDTO.getUnitPrice()+totalPrice;
                         foodmxService.delectFoodIdmx(foodmxDTO.getFoodmxId());
                         ok = false;
                     }else {
                         CollarmxTemDTO collarmxTemDTO = new CollarmxTemDTO();
                         collarmxTemDTO.setBatchNumber(foodmxDTO.getBatchNumber());
                         collarmxTemDTO.setCollarId(collarmxDTO.getCollarId());
                         collarmxTemDTO.setArrivalNum(realCollarNum);
                         collarmxTemDTO.setFoodId(collarmxDTO.getFoodId());
                         collarmxTemDTO.setFoodName(collarmxDTO.getFoodName());
                         collarmxTemDTO.setEntityPhoto(collarmxDTO.getEntityPhoto());
                         collarmxTemDTO.setUnitPrice(foodmxDTO.getUnitPrice());
                         collarmxTemDTO.setCollarNum(collarmxDTO.getCollarNum());
                         collarmxTemDTO.setTotalPrice(foodmxDTO.getUnitPrice()*foodmxDTO.getFoodNum());
                         collarmxTemService.save(collarmxTemDTO);
                         realCollarNum = foodmxDTO.getFoodNum() - realCollarNum;
                         foodmxDTO.setFoodNum(realCollarNum);
                         foodmxService.update(foodmxDTO);
                         totalPrice = realCollarNum*foodmxDTO.getUnitPrice()+totalPrice;
//                         realCollarNum=0F;
                         ok = false;
                     }
                 }
             }
             //保存 领取食材数量的总价
             collarmxDao.updateOrder(collarmxDTO.getCollarmxId(),totalPrice);
         }
     }
    @Transactional
    public void saveCollarOrder(JSONObject params, UserEntity entity) {
        String collarId = (String) params.get("collarId");
        if(StringUtils.isNotBlank(collarId)){
          collarService.deleteById(Long.parseLong(collarId)) ;
          collarmxService.deleteOrder(Long.parseLong(collarId));
        }
        CollarDTO collarDTO = new CollarDTO();
        //食堂id 创建时间，主厨id（创建人）
        collarDTO.setCreateDate(new Date());
        String chedId = (String) params.get("chedId");
        collarDTO.setChedId(Long.parseLong(chedId));
        collarDTO.setCanteenId(entity.getDeptId());
        collarService.save(collarDTO);
        Long collarId1 =  collarDTO.getCollarId();//获取订单id
        ArrayList<LinkedHashMap> list = (ArrayList) params.get("list");
        for (int i = 0; i < list.size(); i++) {
           LinkedHashMap<String, Object> list1 = list.get(i);
         //   String supplierId = (String) list1.get("supplierId");
            ArrayList<LinkedHashMap> foods = (ArrayList) list1.get("foods");
            for (int j = 0; j < foods.size(); j++) {
                CollarmxDTO collarmxDTO = new CollarmxDTO();
                String foodId = (String) foods.get(j).get("foodId");
                collarmxDTO.setFoodId(Long.parseLong(foodId));
                Float num =1F;
                String purchaseNum =String.valueOf(foods.get(j).get("purchaseNum"));
                System.out.println(purchaseNum);
                if("null" != purchaseNum || null !=purchaseNum){
                    num =Float.parseFloat(purchaseNum);
                }
                collarmxDTO.setCollarNum(num);
                collarmxDTO.setFoodName((String) foods.get(j).get("foodName"));
                collarmxDTO.setCollarId(collarId1);
                collarmxService.save(collarmxDTO);
            }
        }
        TemporaryOrderDTO temOrder = temporaryOrderService.getTemOrder(3, entity.getId(), entity.getDeptId());
        temporaryOrderService.deleteOrder(3,entity.getDeptId());
        temporaryOrdermxService.deleteOrder(temOrder.getTemporaryId());
    }

    @Override
    public List<CollarDTO> home(Map<String, Object> params,UserEntity entity) {
        QueryWrapper<CollarEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_date");
        List<CollarEntity> list = baseDao.selectList(queryWrapper);

        return ConvertUtils.sourceToTarget(list, CollarDTO.class);
    }

    /**
     * 仓储员查询接口
     * @param params
     * @return
     */
    @Override
    public PageData<CollarDTO> pagesTorehouseClerk(Map<String, Object> params,UserEntity entity) {

        QueryWrapper<CollarEntity> wrapper = new QueryWrapper<>();
        wrapper.ge("status",3);
        wrapper.eq("canteen_id",entity.getDeptId()).orderByDesc("create_date");
        IPage<CollarEntity> page = baseDao.selectPage(
                getPage(params, null, false),
                wrapper
        );
        return getPageData(page, CollarDTO.class);
    }

    /**
     * 食堂管理员查询接口
     * @param params
     * @return
     */
    @Override
    public PageData<CollarDTO> pageAdmin(Map<String, Object> params) {
        String canteenid = (String)params.get("canteenId");
        QueryWrapper<CollarEntity> wrapper = new QueryWrapper<>();
        wrapper.ge("status",1);
        wrapper.orderByDesc("create_date");
        wrapper.eq(StringUtils.isNotBlank(canteenid),"canteen_id", Long.parseLong(canteenid));
        IPage<CollarEntity> page = baseDao.selectPage(
                getPage(params, null, false),
                wrapper
        );
        return getPageData(page, CollarDTO.class);
    }

    @Override
    public PageData<CollarDTO> getOrder(Map<String, Object> params, UserEntity entity) {
        QueryWrapper<CollarEntity> wrapper = new QueryWrapper<>();
        wrapper.eq( "ched_id", entity.getId());
        wrapper.orderByDesc("create_date");
        IPage<CollarEntity> page = baseDao.selectPage(
                getPage(params, null, false),
                wrapper
        );
        PageData<CollarDTO> pageData = getPageData(page, CollarDTO.class);
        return pageData;
    }

    @Override
    public CollarDTO getTotal(Long chedId, Long clerkId, Long canteenId, int status) {
        String ched_Id="";
        String clerk_Id="";
        String canteen_Id="";
        if(null != chedId){
            ched_Id = " and  ched_id = "+chedId;
        }
        if(null != clerkId){
            clerk_Id = " and  canteen_admin_id = "+clerkId;
        }
        if(null != canteenId){
            canteen_Id = " and  canteen_id = "+canteenId;
        }
        CollarDTO total = collarDao.getTotal(ched_Id, clerk_Id, canteen_Id, status);
        return total;
    }
}